package com.ruoyi.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.UncheckDraft;
import com.ruoyi.service.IUncheckDraftService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 未审核文章草稿箱Controller
 *
 * @author ruoyi
 * @date 2025-09-14
 */
@RestController
@RequestMapping("/uncheck/draft")
public class UncheckDraftController extends BaseController
{
    @Autowired
    private IUncheckDraftService uncheckDraftService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 判断部门是否直接隶属于荆州市长江河道管理局（一级子部门）
     * @param dept 部门信息
     * @param sysDeptMapper 部门Mapper
     * @return 是否直接隶属于荆州市长江河道管理局
     */
    private static boolean isDirectSubDeptOfJingZhou(SysDept dept, SysDeptMapper sysDeptMapper) {
        // 如果部门本身就是"荆州市长江河道管理局"，则不认为是其下级部门
        if ("荆州市长江河道管理局".equals(dept.getDeptName())) {
            return false;
        }

        // 直接检查父部门是否为"荆州市长江河道管理局"
        // 如果父部门ID有效，直接查询父部门名称
        if (dept.getParentId() != null && dept.getParentId() > 0) {
            SysDept parentDept = sysDeptMapper.selectDeptById(dept.getParentId());
            if (parentDept != null && "荆州市长江河道管理局".equals(parentDept.getDeptName())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断部门是否为市局/总局或其子部门
     * @param dept 部门信息
     * @param sysDeptMapper 部门Mapper
     * @return 是否为市局/总局或其子部门
     */
    private static boolean isCityBureauOrSubordinate(SysDept dept, SysDeptMapper sysDeptMapper) {
        if (dept == null) {
            return false;
        }

        // 如果当前部门就是市局/总局，直接返回true
        if ("市局/总局".equals(dept.getDeptName())) {
            return true;
        }

        // 通过祖先部门查找是否属于市局/总局
        String ancestors = dept.getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");

            // 查询祖先部门中是否有市局/总局
            for (String ancestorId : ancestorIds) {
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        if (ancestorDept != null && "市局/总局".equals(ancestorDept.getDeptName())) {
                            return true;
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }

        return false;
    }

    /**
     * 获取用户部门对应的文章来源（分局名称）
     * 通过祖先部门查找所属的直接隶属于荆州市长江河道管理局的部门
     */
    private String getDeptArticleOrigin(SysUser sysUser) {
        if (sysUser.getDept() == null) {
            return null;
        }

        // 如果当前部门直接隶属于荆州市长江河道管理局，直接返回
        if (isDirectSubDeptOfJingZhou(sysUser.getDept(), sysDeptMapper)) {
            return sysUser.getDept().getDeptName();
        }

        // 否则通过祖先部门查找
        String ancestors = sysUser.getDept().getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");

            // 查询祖先部门中直接隶属于荆州市长江河道管理局的部门
            for (String ancestorId : ancestorIds) {
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        if (ancestorDept != null && ancestorDept.getDeptName() != null &&
                                isDirectSubDeptOfJingZhou(ancestorDept, sysDeptMapper)) {
                            return ancestorDept.getDeptName();
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }

        return null;
    }

    /**
     * 查询未审核文章草稿箱列表
     */
    //@PreAuthorize("@ss.hasPermi('uncheck:draft:list')")
    @GetMapping("/list")
    public TableDataInfo list(UncheckDraft uncheckDraft)
    {
        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        // 判断用户权限类型
        boolean isSuperAdmin = "admin".equals(sysUser.getUserName());

        if (!isSuperAdmin) {
            // 所有非管理员用户都根据部门名称查询自己的草稿数据
            if (sysUser.getDept() != null && sysUser.getDept().getDeptName() != null) {
                uncheckDraft.setDeptName(sysUser.getDept().getDeptName());
            }
            // 兜底情况：根据创建者查询
            else {
                uncheckDraft.setCreateBy(sysUser.getUserName());
            }
        }

        startPage();
        List<UncheckDraft> list = uncheckDraftService.selectUncheckDraftList(uncheckDraft);
        return getDataTable(list);
    }

    /**
     * 导出未审核文章草稿箱列表
     */
    //@PreAuthorize("@ss.hasPermi('uncheck:draft:export')")
    @Log(title = "未审核文章草稿箱", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UncheckDraft uncheckDraft)
    {
        List<UncheckDraft> list = uncheckDraftService.selectUncheckDraftList(uncheckDraft);
        ExcelUtil<UncheckDraft> util = new ExcelUtil<UncheckDraft>(UncheckDraft.class);
        util.exportExcel(response, list, "未审核文章草稿箱数据");
    }

    /**
     * 获取未审核文章草稿箱详细信息
     */
    //@PreAuthorize("@ss.hasPermi('uncheck:draft:query')")
    @GetMapping(value = "/{articleId}")
    public AjaxResult getInfo(@PathVariable("articleId") Long articleId)
    {
        return success(uncheckDraftService.selectUncheckDraftByArticleId(articleId));
    }

    /**
     * 新增未审核文章草稿箱
     */
    //@PreAuthorize("@ss.hasPermi('uncheck:draft:add')")
    @Log(title = "未审核文章草稿箱", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UncheckDraft uncheckDraft)
    {
        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        // 设置创建者信息
        uncheckDraft.setCreateBy(sysUser.getUserName());
        uncheckDraft.setUpdateBy(sysUser.getUserName());

        // 设置部门名称
        if (sysUser.getDept() != null && sysUser.getDept().getDeptName() != null) {
            uncheckDraft.setDeptName(sysUser.getDept().getDeptName());
        }

        // 设置创建时间和更新时间
        Date now = new Date();
        uncheckDraft.setCreateTime(now);
        uncheckDraft.setUpdateTime(now);

        // 设置草稿状态
        uncheckDraft.setStatus(0); // 0表示草稿状态

        return toAjax(uncheckDraftService.insertUncheckDraft(uncheckDraft));
    }

    /**
     * 修改未审核文章草稿箱
     */
    //@PreAuthorize("@ss.hasPermi('uncheck:draft:edit')")
    @Log(title = "未审核文章草稿箱", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UncheckDraft uncheckDraft)
    {
        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        // 设置更新者信息
        uncheckDraft.setUpdateBy(sysUser.getUserName());

        // 设置更新时间
        uncheckDraft.setUpdateTime(new Date());

        // 更新部门名称
        if (sysUser.getDept() != null && sysUser.getDept().getDeptName() != null) {
            uncheckDraft.setDeptName(sysUser.getDept().getDeptName());
        }

        return toAjax(uncheckDraftService.updateUncheckDraft(uncheckDraft));
    }

    /**
     * 删除未审核文章草稿箱
     */
    //@PreAuthorize("@ss.hasPermi('uncheck:draft:remove')")
    @Log(title = "未审核文章草稿箱", businessType = BusinessType.DELETE)
    @DeleteMapping("/{articleIds}")
    public AjaxResult remove(@PathVariable Long[] articleIds)
    {
        return toAjax(uncheckDraftService.deleteUncheckDraftByArticleIds(articleIds));
    }

    /**
     * 发布未审核文章草稿箱
     */
    //@PreAuthorize("@ss.hasPermi('uncheck:draft:edit')")
    @Log(title = "未审核文章草稿箱", businessType = BusinessType.UPDATE)
    @PostMapping("/publish/{articleId}")
    public AjaxResult publishDraft(@PathVariable Long articleId)
    {
        try {
            // 检查草稿是否存在
            UncheckDraft draft = uncheckDraftService.selectUncheckDraftByArticleId(articleId);
            if (draft == null) {
                return error("草稿不存在");
            }

            // 检查是否上传了审批表
            if (draft.getAppval() == null || draft.getAppval().isEmpty()) {
                return error("请上传审批表");
            }

            // 发布草稿
            int result = uncheckDraftService.publishUncheckDraft(articleId);
            if (result > 0) {
                return success("发布成功");
            } else {
                return error("发布失败");
            }
        } catch (RuntimeException e) {
            return error(e.getMessage());
        }
    }
}